﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Utility
{
    public class Utils
    {
        public static int StrToInt(object strValue, int defValue)
        {
            if ((strValue == null) || (strValue.ToString() == string.Empty))
            {
                return defValue;
            }

            int value = defValue;
            try
            {
                value = Convert.ToInt32(strValue);
            }
            catch
            {
                value = defValue;
            }
            return value;
        }

        /// <summary>
        /// string型转换为float型
        /// </summary>
        /// <param name="strValue">要转换的字符串</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>转换后的int类型结果</returns>
        public static float StrToFloat(object strValue, float defValue)
        {
            if ((strValue == null) || (strValue.ToString() == string.Empty))
            {
                return defValue;
            }

            float value = defValue;
            try
            {
                value = Convert.ToSingle(strValue);
            }
            catch
            {
                value = defValue;
            }
            return value;
        }

        public static double StrToDouble(object strValue, double defValue)
        {
            if ((strValue == null) || (strValue.ToString() == string.Empty))
            {
                return defValue;
            }

            double value = defValue;
            try
            {
                value = Convert.ToDouble(strValue);
            }
            catch
            {
                value = defValue;
            }
            return value;
        }

        public static bool IsIP(string ip)
        {
            return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }
    }
}
